from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from app.database import get_db
from app.models.exam import Exam, ExamStatus, ExamType
from app.models.user import User, UserRole
from app.schemas.exam import ExamCreate, ExamUpdate, ExamResponse, ExamList, ExamForStudent
from app.auth import get_current_active_user, get_current_teacher, get_current_admin

router = APIRouter()

@router.get("/", response_model=ExamList)
async def get_exams(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    status_filter: Optional[ExamStatus] = Query(None, description="考试状态筛选"),
    exam_type: Optional[ExamType] = Query(None, description="考试类型筛选"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取考试列表"""
    query = db.query(Exam).filter(Exam.is_deleted == False)
    
    # 权限过滤
    if current_user.role == UserRole.TEACHER:
        query = query.filter(Exam.created_by == current_user.id)
    
    if status_filter:
        query = query.filter(Exam.status == status_filter)
    
    if exam_type:
        query = query.filter(Exam.exam_type == exam_type)
    
    if search:
        query = query.filter(
            or_(
                Exam.title.contains(search),
                Exam.description.contains(search)
            )
        )
    
    total = query.count()
    exams = query.offset(skip).limit(limit).all()
    
    # 添加创建者信息
    result = []
    for exam in exams:
        creator = db.query(User).filter(User.id == exam.created_by).first()
        exam_dict = {
            **exam.__dict__,
            "creator": {
                "id": creator.id,
                "username": creator.username,
                "full_name": creator.full_name
            }
        }
        result.append(exam_dict)
    
    return {"total": total, "items": result}

@router.get("/available", response_model=List[ExamForStudent])
async def get_available_exams(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取学生可参加的考试"""
    now = datetime.utcnow()
    exams = db.query(Exam).filter(
        and_(
            Exam.is_deleted == False,
            Exam.status == ExamStatus.PUBLISHED,
            Exam.start_time <= now,
            Exam.end_time >= now
        )
    ).all()
    
    return exams

@router.get("/{exam_id}", response_model=ExamResponse)
async def get_exam(
    exam_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取考试详情"""
    exam = db.query(Exam).filter(Exam.id == exam_id, Exam.is_deleted == False).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 权限检查
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能查看自己创建的考试"
        )
    
    creator = db.query(User).filter(User.id == exam.created_by).first()
    return {
        **exam.__dict__,
        "creator": {
            "id": creator.id,
            "username": creator.username,
            "full_name": creator.full_name
        }
    }

@router.post("/", response_model=ExamResponse)
async def create_exam(
    exam_data: ExamCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """创建考试"""
    db_exam = Exam(**exam_data.dict(), created_by=current_user.id)
    db.add(db_exam)
    db.commit()
    db.refresh(db_exam)
    
    return {
        **db_exam.__dict__,
        "creator": {
            "id": current_user.id,
            "username": current_user.username,
            "full_name": current_user.full_name
        }
    }

@router.put("/{exam_id}", response_model=ExamResponse)
async def update_exam(
    exam_id: int,
    exam_data: ExamUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """更新考试"""
    exam = db.query(Exam).filter(Exam.id == exam_id, Exam.is_deleted == False).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 权限检查
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能更新自己创建的考试"
        )
    
    # 更新字段
    for field, value in exam_data.dict(exclude_unset=True).items():
        setattr(exam, field, value)
    
    db.commit()
    db.refresh(exam)
    
    creator = db.query(User).filter(User.id == exam.created_by).first()
    return {
        **exam.__dict__,
        "creator": {
            "id": creator.id,
            "username": creator.username,
            "full_name": creator.full_name
        }
    }

@router.delete("/{exam_id}")
async def delete_exam(
    exam_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """删除考试"""
    exam = db.query(Exam).filter(Exam.id == exam_id, Exam.is_deleted == False).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 权限检查
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能删除自己创建的考试"
        )
    
    exam.is_deleted = True
    db.commit()
    return {"message": "考试删除成功"}

@router.get("/stats/count")
async def get_exam_stats(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """获取考试统计信息"""
    query = db.query(Exam).filter(Exam.is_deleted == False)
    
    if current_user.role == UserRole.TEACHER:
        query = query.filter(Exam.created_by == current_user.id)
    
    total = query.count()
    
    return {
        "total": total,
        "draft": query.filter(Exam.status == ExamStatus.DRAFT).count(),
        "published": query.filter(Exam.status == ExamStatus.PUBLISHED).count(),
        "ongoing": query.filter(Exam.status == ExamStatus.ONGOING).count(),
        "completed": query.filter(Exam.status == ExamStatus.COMPLETED).count()
    }